package com.anlogic.sdk.bsp.utils;

import java.util.ArrayList;
import java.util.List;

import org.apache.logging.log4j.Logger;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;

import com.anlogic.sdk.bsp.model.IPlatformProject;
import com.anlogic.sdk.bsp.model.PlatformProject;
import com.anlogic.sdk.bsp.model.PlatformProjectNature;
import com.anlogic.sdk.utils.LogUtils;

public class PlatformUtils {
	private static Logger logger = LogUtils.getLogger(PlatformUtils.class);
	
	public static List<IPlatformProject> getPlatformProjectsInWorkspace() {
		return getPlatformProjectsInWorkspace(ResourcesPlugin.getWorkspace().getRoot());
	}
	
	public static List<IPlatformProject> getPlatformProjectsInWorkspace(IWorkspaceRoot root) {
		ArrayList<IPlatformProject> platformProjects = new ArrayList<IPlatformProject>();
		for(IProject project: root.getProjects()) {
			try {
				if (PlatformProjectNature.isPlatformProject(project)) {
					IPlatformProject platformProject = new PlatformProject(project);
					platformProject.restoreMetaData();
					platformProjects.add(platformProject);
				}
			} catch (CoreException e) {
				logger.error("Get platform projects error {}", e.getMessage());
			}
		}
		
		return platformProjects;
	}
	
	public static IPlatformProject getPlatformProject(String projName) {
		IPlatformProject platformProj = null;
		for (IPlatformProject proj : getPlatformProjectsInWorkspace()) {
			if (proj.getName().equals(projName)) {
				platformProj = proj;
			}
		}
		return platformProj;
	}
	
	public static IPlatformProject getPlatformProjectFromIProject(IProject project) {
		IPlatformProject platformProject = null;
		try {
			if(PlatformProjectNature.isPlatformProject(project)) {
				platformProject = new PlatformProject(project);
				platformProject.restoreMetaData();
			}
		} catch (CoreException e) {
			logger.error("Get platform project error {}", e.getMessage());
		}
		return platformProject;
	}
}
